<template>
    <div ref="vmGPUPart" class="height-per-100">
		<div class="tableCon" style="height: 230px;">
			<ics-el-table
				ref="gpuTable"
				name="gpuTable"
				data-type="dataGrid"
				v-validate-easy="rules.table"
				:config="gpuTableConfig"
				:localData="gpuTableConfig.localTableData"
				@selectRow="selectRow"
				@loadComplete="loadComplete">
			</ics-el-table>
		</div>
		<el-divider></el-divider>
		<div style="border-top: 1px solid #ddd; padding-top: 10px; height: calc(100% - 230px); overflow-y: auto;">
			<el-form label-width="120px" ref="gpuForm" v-if="gpuShow">
				<div>
					<el-form-item label="GPU组名称">
						<el-select
							v-model="gpu.gpuGroup.id"
							@change="changeGroup"
							name="currentGpu"
							data-type="input"
							v-validate-easy="rules.currentGpu">
								<el-option
									v-for="item in gpuGroupNameArray"
									:key="item.gpuGroup.id"
									:value="item.gpuGroup.id"
									:label="item.gpuGroup.name">
								</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="GPU组设备型号">
						<el-input v-model="gpu.gpuGroup.boundGPUProductName" readonly></el-input>
					</el-form-item>
					<el-form-item label="使用方式">
						<el-input
						ref="useType"
						v-model="useType"
						name="useType"
						data-type="input"
						v-validate-easy="rules.useType"
						readonly></el-input>
					</el-form-item>
					<el-form-item label="关机后释放">
						<el-checkbox v-model="gpu.releaseAfterPowerOff" :disabled="vmStatus">
							是否关机后释放
						</el-checkbox>
						<el-tooltip placement="right">
							<div slot="content" v-html="gpuReleaseTip"></div>
							<span class="icon-info ics-icon-tooltip"></span>
						</el-tooltip>
					</el-form-item>
					<el-form-item label="提示" class="ics-hinttext">
						windows虚拟机使用vGPU设备时，需要通过远程方式登录
					</el-form-item>
				</div>
			</el-form>
		</div>
	</div>
</template>

<script>
export default {
	name: 'gpu',
	props: {
		vmData: {},
		modetype: {},
		hostData: {},
		options: {},
		addNew: {default: false}
	},
	data () {
		return {
			ref: 'vmGPUPart',
			gpuTableConfig: {
				localTableData: [],
				mode: 'local',
				showRadio: true,
				columns: [
					{
						name: 'id',
						index: 'id',
						hidden: 'true'
					},
					{
						name: 'GPU序号',
						index: 'gpuIndex'
					},
					{
						name: 'GPU名称',
						index: 'name'
					},
					{
						name: '设备名称',
						index: 'boundGPUProductName'
					},
					{
						name: '使用方式',
						index: 'groupType'
					}
				],
				beforeSelect: this.beforeSelect
			},
			vmGpu: {
				gpus: []
			},
			gpuGroupNameArray: [],
			hasGet: false,
			bAdd: false,
			gpu: {
				gpuGroup: {},
				releaseAfterPowerOff: false
			},
			gpuShow: false,
			activeIndex: 0,
			gpuIndex: 1,
			defaultGpu: {
				gpuGroup: {
					id: '',
					name: '',
					boundGPUProductName: '',
					groupType: ''
				},
				releaseAfterPowerOff: false
			},
			gpuReleaseTip: '关闭虚拟机后自动释放GPU设备资源',
			rules: {
				table: [
					['required', '该输入项不能为空。']
				],
				currentGpu: [
					['required', 'GPU组名称不能为空。']
				],
				useType: [
					['isVGPU']
				]
			}
		};
	},
	computed: {
		useType () {
			return this.gpu.gpuGroup.groupType !== 'VIRTUAL_FUNCTION' ? '直通' : 'vGPU';
		},
		vmStatus () {
			return this.vmData.status && this.vmData.status === 'STARTED';
		}
	},
	watch: {
		'vmGpu.gpus': {
			handler (newVal, oldVal) {
				this.setTableData();
				this.$emit('updateVmDate', 'vmGPUPart', newVal);
			},
			deep: true
		},
		options: {
			handler (newVal, oldVal) {
				if (newVal.currentTabName === 'vmGPUPart') {
					if (newVal.addNew) {
						this.addGpu();
						this.$emit('changeAddOrDel', 'addNew', false);
					}
					if (newVal.delOne) {
						this.delGpu();
						this.$emit('changeAddOrDel', 'delOne', false);
					}
				}
			},
			deep: true
		}
	},
	created () {
		let that = this;
		// var a = 1;
		that.getGpuData().then(() => {
			if (!(that.gpuGroupNameArray && that.gpuGroupNameArray.length)) {
				that.gpuGroupNameArray.push(JSON.parse(JSON.stringify(that.defaultGpu)));
			}
			if (that.vmData && that.vmData.gpus && that.vmData.gpus.length) {
				that.vmData.gpus.forEach((item, index) => {
					item.gpuIndex = that.gpuIndex++;
					that.vmGpu.gpus.push(item);
				});
			} else {
				that.gpuGroupNameArray[0].gpuIndex = that.gpuIndex++;
				that.vmGpu.gpus.push(JSON.parse(JSON.stringify(that.gpuGroupNameArray[0])));
			}
			that.activeIndex = that.vmGpu.gpus.length - 1;
			this.$emit('changeAddOrDel', 'addNew', false);
		});
	},
	beforeMount () {
		this.V.$addValidateMethod('isVGPU', (value, obj) => {
			let pasNum = 0;
			let vgpuNum = 0;
			this.vmGpu.gpus.forEach(item => {
				if (item.gpuGroup.groupType === 'VIRTUAL_FUNCTION') {
					vgpuNum++;
				} else {
					pasNum++;
				}
			});
			if ((value === 'vGPU' && vgpuNum > 1) || (vgpuNum > 0 && pasNum > 0)) {
				return '多块GPU设备仅支持直通的使用方式';
			}
			return '';
		});
	},
	methods: {
		getGpuData () {
			let that = this;
			return this.ser.get('/gpugroups?type=inclusterofhost&hostId=' + this.vmData.hostId).then(res => {
				res.data.forEach(item => {
					that.gpuGroupNameArray.push({
						'gpuGroup': {
							'id': item.id,
							'name': item.name,
							'groupType': item.groupType,
							'boundGPUProductName': item.boundGPUProductName
						},
						'releaseAfterPowerOff': true
					});
				});
				that.hasGet = true;
			});
		},
		setTableData () {
			this.gpuTableConfig.localTableData = [];
			this.vmGpu.gpus.forEach((item, index) => {
				this.gpuTableConfig.localTableData.push({
					id: index,
					gpuIndex: 'GPU' + item.gpuIndex,
					name: item.gpuGroup.name,
					boundGPUProductName: item.gpuGroup.boundGPUProductName,
					gpuType: item.gpuGroup.gpuType !== 'VIRTUAL_FUNCTION' ? '直通' : 'vGPU'
				});
			});
		},
		changeGroup (val) {
			this.gpuGroupNameArray.forEach(item => {
				if (this.gpu.gpuGroup.id === item.gpuGroup.id) {
					this.utils.deepMerge(this.gpu.gpuGroup, item.gpuGroup);
					this.gpu.releaseAfterPowerOff = item.releaseAfterPowerOff;
				}
			});
			this.validate();
		},
		addGpu () {
			if (this.vmGpu.gpus.length >= 4) {
				let that = this;
				that.$vConfirm({
					content: '虚拟机只支持四个GPU设备。请删除当前GPU设备，再继续增加新的GPU设备',
					confirmType: that.enums.ConfirmEnum.INFO_WARNING_ONE
				});
				return;
			}
			this.bAdd = true;
			if (this.hasGet && !(this.gpuGroupNameArray && this.gpuGroupNameArray.length)) {
				this.gpuGroupNameArray.push(JSON.parse(JSON.stringify(this.defaultGpu)));
			}
			this.vmGpu.gpus.push(JSON.parse(JSON.stringify(this.gpuGroupNameArray[0])));
			this.vmGpu.gpus[this.vmGpu.gpus.length - 1].gpuIndex = this.gpuIndex++;
		},
		delGpu () {
			this.bDel = true;
			this.vmGpu.gpus.splice(this.activeIndex, 1);
			if (this.vmGpu.gpus.length) {
				this.gpu = Object.assign({}, this.vmGpu.gpus[0]);
				this.activeIndex = 0;
			} else {
				this.$emit('changeAddOrDel', 'delTab');
			}
		},
		beforeSelect () {
			let that = this;
			return new Promise((resolve, reject) => {
				let data = {
					canSubmit: true
				};
				if (that.$refs.gpuForm) {
					return that.V.$validateAll(that.$refs.gpuForm.$el).then((success) => {
						resolve(success || data);
					}, (error) => {
						resolve(error || data);
					});
				}
				return resolve(data);
			});
		},
		selectRow (row) {
			this.gpu = this.vmGpu.gpus[row.id];
			this.gpuShow = true;
		},
		loadComplete (data) {
			let canSumit = true;
			this.beforeSelect().then(res => {
				canSumit = res.canSumit;
				if (this.bAdd) {
					if (canSumit) {
						this.activeIndex = this.vmGpu.gpus.length - 1;
					} else {
						//
					}
					this.bAdd = false;
				}
				if (this.bDel) {
					this.activeIndex = 0;
					this.bDel = false;
				}
				this.$refs.gpuTable.cellClick(data[this.activeIndex]);
			});
			this.$refs.gpuTableConfig.cellClick(data[this.activeIndex]);
		},
		validate () {
			this.$nextTick(() => {
				this.V.$validateSingle(this.$refs.useType.$el);
			});
		},
		validTab (v) {
			let that = this;
			if (this.$refs.gpuForm && this.$refs.gpuForm.$el) {
				return new Promise((resolve, reject) => {
					that.V.$validateAll(that.$refs.gpuForm.$el).then(data => {
						if (data.canSubmit) {
							resolve(true);
						} else {
							reject(new Error(false));
						}
					});
				});
			}
			return true;
		}
	}
};
</script>
